﻿using System;
using System.Collections.Generic;
using System.Text;
namespace RuoTeng.Util.Update
{
    using System.IO;
    using System.Net;
    using System.Text.RegularExpressions;

    public struct VersionFile
    {
        public string Name;
        public string RemoteAddress;
        public string LocalAddress;            
    }
    class UpdateVersion
    {     
        protected static string UpdateProcessName=UpdateConfig.GetValue("ProcessName");
        public static string  GetLatestVersion()
        {
            string version = null;
           
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(UpdateConfig.GetValue("VersionURL"));
                request.Timeout=3000;
                //request.GetRequestStream().Close();
                StreamReader stream    = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.Default);
                version = stream.ReadToEnd();
                stream.Close();
            }
            catch (Exception)
            {
            }
            return version;
        }

        public static bool HaveNewVersion()
        {
            string[] array_cVersion = UpdateConfig.GetValue("Version").Split('.');
            string str = GetLatestVersion();
            string[] array_nVersion=new string[0];
            if(str!=null)array_nVersion=str.Split('.');
            int max = array_cVersion.Length > array_nVersion.Length ? array_cVersion.Length : array_nVersion.Length;
            long  __cVersion =0;   long  __nVersion =0;

            for (int i = 0; i < max; i++)
            {
                int __c = 0; int __n = 0; int __cL = 1; int __nL = 1;
                int __cPow =(max - i) - 1;
                int __nPow =(max - i) - 1;
                if (i < array_cVersion.Length && int.TryParse(array_cVersion[i], out __c))
                {
                    __cL = array_cVersion[i].Length;
                }
                if (i < array_nVersion.Length && int.TryParse(array_nVersion[i], out __n))
                {
                    __nL = array_nVersion[i].Length;
                }
                if (__cL > __nL)
                {
                    __nPow +=(__cL-__nL);
                }
                if (__cL < __nL)
                {
                    __cPow +=(__nL-__nL);
                }
                __cVersion += __c * (int)System.Math.Pow(10, __cPow);
                __nVersion += __n * (int)System.Math.Pow(10, __nPow);
            }
            return __cVersion < __nVersion ? true : false;
        }

        public static List<VersionFile> GetVerionFile()
        {
            List<VersionFile> File=new List<VersionFile>();
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(UpdateConfig.GetValue("UpdateURL"));
                request.Timeout=3000;
                StreamReader   stream  = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.Default);
                string         Str     = stream.ReadToEnd();
                string[]       AFile   = Str.Split(',');
                foreach (string Name in AFile)
                {
                    string[] result = Regex.Split(Name,"\\/(.+?)$",RegexOptions.RightToLeft);
                    if (result.Length > 1)
                    {
                        VersionFile v = new VersionFile();
                        v.RemoteAddress = Name;
                        v.Name = result.Length > 1 ? result[1] : "";
                        v.LocalAddress = result.Length > 1 ? "./update/" + result[1] : "unkown";
                        File.Add(v);
                    }
                }
                stream.Close();
            }
            catch (Exception)
            {
               
            } 
            return File;
        }

        public static bool IsStartProcess()
        {
            if (UpdateProcessName != null)
            {
                System.Diagnostics.Process[] process= System.Diagnostics.Process.GetProcessesByName(UpdateProcessName);
                if (process.Length > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool StopProcess()
        {
            if (UpdateProcessName != null)
            {
                System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(UpdateProcessName);
                foreach( System.Diagnostics.Process p in process)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        public static bool BackupApplication()
        {
            if (!Directory.Exists("backup"))
            {
                Directory.CreateDirectory("backup");
            }
            if (Directory.Exists("backup"))
            {   
                string [] fileList=Directory.GetFileSystemEntries(".");
                foreach(string file in fileList)
                {
                     if(!Directory.Exists(file))
                     {
                         File.Copy(file,"backup/"+System.IO.Path.GetFileName(file),true);
                     }
                }
                return true;
            }
            return false;
        }

        public static bool Install()
        {
            if (Directory.Exists("update"))
            {
                string[] fileList = Directory.GetFileSystemEntries("update");
                foreach (string file in fileList)
                {
                    if (!Directory.Exists(file))
                    {
                        string name = System.IO.Path.GetFileName(file);
                        if (File.Exists(name))
                        {
                            File.Delete(name);
                        }
                        File.Copy(file, System.IO.Path.GetFileName(file));
                    }
                }
                Directory.Delete("update",true);
                Directory.Delete("backup",true);
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool StartApplication()
        {
            try
            {
                System.Diagnostics.Process p = System.Diagnostics.Process.Start(UpdateProcessName);
                return true;
            }
            catch(Exception){
                return false;
            }
        }
    }
}
